package wiki.tools.vidition.droid.util;

import java.util.ArrayList;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import wiki.tools.vidition.droid.util.bean.RSSItem;


import android.text.TextUtils;

public class SeaxParssRSS extends DefaultHandler {
	private ArrayList<RSSItem> rss;
	private Stack<String> stack;
	StringBuilder builder;
	RSSItem item;

	public SeaxParssRSS() {
		stack = new Stack<String>();
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub

		String temp = new String(ch, start, length);
		if (!TextUtils.isEmpty(temp)) {
			builder.append(temp);
		}
		super.characters(ch, start, length);
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		String node = stack.pop();
		if(stack.size() == 0) {
			return;
		}
		boolean isNewItem = stack.peek().equals("Item") ? true : false;
		String value = builder.toString();
		if (node.equals("Text") && isNewItem) {
			item.text = value;
		} else if (node.equals("Description") && isNewItem) {
			item.description = value;
		} else if (isNewItem && node.equals("Url")) {
			item.webUrl = value;
		} else if (node.equals("Item")) {
			rss.add(item);
		}
		super.endElement(uri, localName, name);
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		if (localName.equals("SearchSuggestion")) {
			rss = new ArrayList<RSSItem>();
		} else if (localName.equals("Item")) {
			item = new RSSItem();
		} else if (localName.equals("Image")) {
			item.imageurl = attributes.getValue("source");
		}
		stack.push(localName);
		builder = new StringBuilder();
		super.startElement(uri, localName, name, attributes);

	}

	public ArrayList<RSSItem> getRSS() {
		return rss;
	}
}